package com.svm.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.svm.bean.SvmClass;

public class SvmClassUtils {

	public static void saveSvmClass(SvmClass svmClass) {

		try {

			File file = new File(SystemConfig.XML_REPOSITOTY
					+ svmClass.getName().toLowerCase() + ".xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(SvmClass.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			jaxbMarshaller.marshal(svmClass, file);

		} catch (JAXBException ex) {
			System.out.println(ex);
		}

	}

	public static List<SvmClass> listSvmClass() {
		List<SvmClass> classes = new ArrayList<SvmClass>();

		try {
			File directory = new File(SystemConfig.XML_REPOSITOTY);

			if (directory.isDirectory()) {
				for (File file : directory.listFiles()) {
					JAXBContext jaxbContext = JAXBContext
							.newInstance(SvmClass.class);

					Unmarshaller jaxbUnmarshaller = jaxbContext
							.createUnmarshaller();
					SvmClass svmClass = (SvmClass) jaxbUnmarshaller
							.unmarshal(file);
					classes.add(svmClass);
				}
			}

		} catch (JAXBException ex) {
			System.out.println(ex);
		}
		return classes;
	}

	public static void deleteSvmClasses() {

		File directory = new File(SystemConfig.XML_REPOSITOTY);

		for (File file : directory.listFiles()) {
			file.delete();
		}

	}
}
